package com.anrongtec.zcpt.tab01;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.TextView;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.module.PageList;
import com.anrongtec.zcpt.module.AppModel;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.Util;
import com.ansec.mdm.IPackageService;
import com.art.base.util.ApkUtils;
import com.google.gson.reflect.TypeToken;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.utils.MyItemDecoration;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;
import com.zhy.adapter.recyclerview.wrapper.LoadMoreWrapper;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

import static com.art.base.db.LiteOrmDBUtil.mContext;

public class AppsUnloadActivity extends BaseActivity {


    private RecyclerView rv;

    private WebView webView;

    private SwipeRefreshLayout swipe_refresh;
    private CommonAdapter<AppModel> adapter;
    //	private List<FunctionModel> functions;
    private List<AppModel> apps, newApps;
    private List<AppModel> appsList;
    private AppModel tempApp;
    private TextView tv_header;
    private EmptyWrapper empty;
    private LoadMoreWrapper loadMoreWrapper;
    private static final int SPAN_COUNT = 4;
    private List datas;//获取本地安装应用与商店存在应用相同 的应用信息

    private IPackageService mPackageService;//卸载器

    private boolean isGetAppsInfo = true;//是否正在获取app信息

    private final static int GET_APPS_FROM_SERVER = 2;//从服务器获取本地安装与商店相同的数据

    private Animation in, out;
    private ProgressDialog mLoadingDialog;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mLoadingDialog.dismiss();
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    empty.setEmptyView(R.layout.empty_view);
                    rv.setAdapter(empty);
                    apps.clear();
//                    apps.addAll(newApps);
                    apps.addAll(appsList);
                    LogUtil.e("获取应用数量" + apps.size());
                    empty.notifyDataSetChanged();
                    if (swipe_refresh != null && swipe_refresh.isRefreshing()) {
                        swipe_refresh.setRefreshing(false);
                    }
                    break;
                case GET_APPS_FROM_SERVER://暂时废弃
                    getAppsInfoFromServer();
                    break;
                default:
                    break;
            }

        }
    };

    // 从服务器获取本地安装与商店相同的数据
    private void getAppsInfoFromServer() {
//        final String requestJson = GsonUtil.toTypeQueryApps(appsList);
        final String requestJson = "";
//        String requestJson = GsonUtil.toTypeQueryApps(appsList);
        LogUtil.e("商店相同的请求数据" + requestJson);
        HttpUtil.post(requestJson, new StoreStringCallBack(this) {
            @Override
            public void onResponse(boolean arg0, String json, Request arg2, Response arg3) {
                super.onResponse(arg0, json, arg2, arg3);
                LogUtil.e("商店相同的返回数据" + json);
                JsonDataRestult<PageList<AppModel>> result = GsonUtil.decode(json,
                        new TypeToken<JsonDataRestult<PageList<AppModel>>>() {
                        }.getType());
                newApps.clear();
                if (result != null && result.getData() != null) {
                    LogUtil.e("商店相同的返回解析数据" + result.getData().getApps().toString());
                    for (int i = 0; i < result.getData().getApps().size(); i++) {
                        AppModel appModel = result.getData().getApps().get(i);
                        AppModel appInfoByPkg = Util.getAppInfoByPkg(AppsUnloadActivity.this, appModel.getAppPackName());
                        newApps.add(appInfoByPkg);
                    }
                    handler.sendEmptyMessageDelayed(1, 1000);
                }
            }

            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                super.onError(isFromCache, call, response, e);
                LogUtil.e(e.toString());
            }
        });
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        setContentView(R.layout.activity_apps_unload);
        initViews();
        initIntent();
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        apps = new ArrayList<>();
        newApps = new ArrayList<>();
        appsList = new ArrayList<>();
        getAppsInfo();
    }

    /**
     * 获取非系统应用
     */
    public void getAppsInfo() {

        Util.post(new Runnable() {
            @Override
            public void run() {
                if (appsList != null) {
                    appsList.clear();
                    appsList.addAll(Util.getAppsFromSystem(AppsUnloadActivity.this));
                    handler.sendEmptyMessage(GET_APPS_FROM_SERVER);
                }
            }
        });
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
        initRecyclerView();
        initSwipeRefresh();
    }

    /**
     * 初始化下拉刷新
     *
     * @param
     */
    private void initSwipeRefresh() {
        swipe_refresh = (SwipeRefreshLayout)findViewById(R.id.swipe_tab_manager_refresh);
        swipe_refresh.setEnabled(false);
        swipe_refresh.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipe_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe_refresh.setRefreshing(true);
                getAppsInfo();
            }
        });
    }



    /**
     * 初始化recyclerview
     *
     * @param
     */
    private void initRecyclerView() {
        rv = (RecyclerView)findViewById(R.id.manager_recycler_view);
        rv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        rv.addItemDecoration(new MyItemDecoration(AppsUnloadActivity.this, MyItemDecoration.VERTICAL_LIST));
        adapter = new CommonAdapter<AppModel>(AppsUnloadActivity.this, R.layout.item_tab_manager_apps, apps) {

            @Override
            protected void convert(ViewHolder holder, final AppModel t, int position) {
                holder.setImageDrawable(R.id.iv_tab_manager_item, t.getLocalIcon());
                if(t.getAppPackName().equals("com.anrongvs")){
                    holder.setText(R.id.tv_tab_manager_apps,"ocr扫描");
                }else{
                    holder.setText(R.id.tv_tab_manager_apps, t.getAppName());
                }
                holder.setOnClickListener(R.id.btn_uninstall_manager_apps, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ApkUtils.uninstall(AppsUnloadActivity.this,t.getAppPackName());
                    }
                });
            }

        };
        empty = new EmptyWrapper(adapter);
        empty.setEmptyView(R.layout.loading_view);
        rv.setAdapter(empty);
    }

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mPackageService = IPackageService.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mPackageService = null;
        }
    };

    private void initIntent() {
        Intent intent = new Intent("com.ansec.mdm.action.PackageManager");
        intent.setPackage("com.ansec.mdm");
        mContext.bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }


    public void refresh() {
        getAppsInfo();
    }


}
